package com.dcsgo.v1ch04;

import java.util.Objects;

/**
 * 
 * @ClassName: StudentTest
 * @Description:构造器中传入null引用
 * @author DCSGO
 * @date 2023-11-12 11:59:06
 */
public class StudentTest {
	public static void main(String[] args) {
		var stu = new Student2(111, null);
		System.out.println(stu);
		//不严格输出: 111 unknown
		
		/*
		 * 严格输出:
		 * Exception in thread "main" java.lang.NullPointerException: 学生姓名不能为null
		 * at java.base/java.util.Objects.requireNonNull(Objects.java:233)
		 * at LearningCoreJava/com.dcsgo.v1ch04.Student2.<init>(StudentTest.java:25)
		 * at LearningCoreJava/com.dcsgo.v1ch04.StudentTest.main(StudentTest.java:7)
		 */
	}
}

class Student2 {
	private long id;
	private String name;

	/*
	 * //name传入null 不严格 public Student2(long i, String n) { id = i;
	 * //当n==null时将name赋值为"unknown" name = Objects.requireNonNullElse(n, "unknown");
	 * }
	 */
	// name传入null 严格
	public Student2(long i, String n) {
		id = i;
		name = Objects.requireNonNull(n, "学生姓名不能为null");
	}

	public long getId() {
		return id;
	}

	public String getName() {
		return name;
	}

	public String toString() {
		return id + " " + name;
	}
}